import React, { Fragment } from 'react'

import {
  StyleSheet,
  View,
  Text,
  TextInput
} from 'react-native'

import AlphabetListView from 'react-native-alphabetlistview'
import BasePage from 'src/pageP/base/base-page/index'
import CustomButton from 'src/components/button/CustomButton'
import CustomImage from 'src/components/image/CustomImage'
import { getCityHistory, insertCityHistory } from 'src/utils/RequestAPI'
import { ScaleS, ScaleT, ONE_PIXEL, NAVIGATIONBAR_HEIGHT, HEIGHT } from 'src/utils/ScreenUtil'
import { HansReg } from 'src/utils/RegUtil'
import { CityList } from 'src/utils/ConfigUtil'
import { connect } from 'react-redux'
import {
  UPDATE_LANDMARK_ACTION
} from 'src/store/actions/landmark'
const debounce = require('lodash/debounce')
// const AZ = new Array(26).fill(65).map((e, i) => String.fromCharCode(e + i))
const ListHeight = HEIGHT - NAVIGATIONBAR_HEIGHT - ScaleS(66)
@connect(
  ({ userinfo }) => ({
    userId: userinfo.userId
  }), dispatch => ({
    updateLandmark (...payload) {
      return dispatch(UPDATE_LANDMARK_ACTION(...payload))
    }
  }))
class CommonListCity extends BasePage {
  constructor (props) {
    super(props)
    const {
      navigation: {
        state: { params = {} }
      }
    } = this.props
    const { cityName } = params
    this.state = {
      header: {},
      currentValue: cityName,
      searchValue: '',
      dataSource: {},
      historyCitys: [],
      historyHeight: 0 // 头部高度
    }
  }

  originData = []

  SectionItems = {}

  // SectionItems高度
  componentDidMount () {
    this.originData = CityList.sort(
      (a, b) =>
        a.extra.toLowerCase().charCodeAt() -
          b.extra.toLowerCase().charCodeAt()
    )
    this.throttleOnChangeText()
    const { userId } = this.props
    userId && getCityHistory({}).then(res => {
      const historyCitys = res.data
      this.setState({
        historyCitys
      })
    })
  }

  renderNavigationBarChild () {
    return <Text style={styles.naviTitle}>切换城市</Text>
  }

  childRender () {
    const { currentValue, searchValue, dataSource, historyHeight } = this.state
    return (
      <Fragment>
        <View style={styles.searchCont}>
          <Text style={styles.searchTitle}>{currentValue}</Text>
          <View style={styles.textIputBg}>
            <TextInput
              style={styles.textInput}
              value={searchValue}
              selectionColor="#666666"
              onChangeText={this.onChangeText}
            />
            <CustomButton style={styles.searchBtn}>
              <CustomImage style={styles.searchImg} source={require('@/imgC/company/company_search.png')}/>
            </CustomButton>
          </View>
        </View>
        <AlphabetListView
          style={styles.listContainer}
          data={dataSource}
          cell={this.renderCell}
          cellHeight={ScaleS(50)}
          sectionListItem={this.renderSectionItem}
          sectionHeader={this.renderSectionHeader}
          sectionHeaderHeight={ScaleT(46)}
          header={this.renderHeader}
          headerHeight={historyHeight}
          onCellSelect={this.onCellSelect}
        />
      </Fragment>
    )
  }

  renderSectionItem = ({ title }) => {
    return <Text style={[styles.sectionText, this.SectionItems[title]]}>{title}</Text>
  }

  renderSectionHeader = ({ title }) => {
    return <Text style={styles.sectionHeaderTit}>{title}</Text>
  }

  renderCell = ({ item }) => {
    return <CustomButton style={styles.cell} params={item} onPress={this.cellClick}>
      <Text style={styles.cellTit}>{item}</Text>
    </CustomButton>
  }

  renderHeader = () => {
    const { userId } = this.props
    const { historyCitys } = this.state
    return (
      userId
        ? <View style={styles.headerContainer} onLayout={this.onHeaderLayout}>
          <Text style={styles.historyTip}>最近登录</Text>
          <View style={styles.historyCitys}>{historyCitys.map(city =>
            <CustomButton key={city} style={styles.cityBtn} params={city} onPress={this.historyItemClick}>
              <Text style={styles.cityText}>{city}</Text>
            </CustomButton>)}</View>
        </View> : null
    )
  }

  onHeaderLayout = ({ nativeEvent: { layout: { height: historyHeight } } }) => {
    if (historyHeight > this.state.historyHeight) {
      console.log('historyHeight', historyHeight)
      this.setState({
        historyHeight
      })
    }
  }

  onChangeText = searchValue => {
    this.setState({
      searchValue
    })
    this.throttleOnChangeText(searchValue)
  }

  throttleOnChangeText = debounce(keyword => {
    const reg = RegExp(keyword)
    const isChinese = keyword && HansReg.test(keyword)
    const temp = this.originData.filter(e => {
      const res = isChinese ? reg.test(e.cityName) : true
      return res
    })
    console.log('onChangeTextDelay', this.originData, keyword, reg, temp)
    const dataSource = temp.reduce((a, b) => {
      a[b.extra] = (a[b.extra] || []).concat([b.cityName])
      return a
    }, {})
    let SectionItems = {}
    const temp1 = temp.filter((e, i) => temp.findIndex(f => f.extra === e.extra) === i).map(e => e.extra)
    const length = temp1.length
    if (length === 1) {
      SectionItems = temp1.reduce((a, b, i) => {
        a[b.extra] = {
          height: ListHeight,
          lineHeight: ListHeight
        }
        return a
      }, {})
    } else if (length > 1) {
      const centerHeight = Math.min(ListHeight / length, ScaleS(30))
      const centerHeights = Math.max((length - 2) * centerHeight, 0)
      SectionItems = temp1.reduce((a, b, i) => {
        let value = 0
        if (i === 0) {
          value = {
            lineHeight: centerHeight,
            height: (ListHeight - centerHeights) / 2,
            paddingTop: (ListHeight - centerHeights) / 2 - centerHeight
          }
        } else if (i === length - 1) {
          value = {
            lineHeight: centerHeight,
            height: (ListHeight - centerHeights) / 2,
            paddingBottom: (ListHeight - centerHeights) / 2 - centerHeight
          }
        } else {
          value = {
            lineHeight: centerHeight,
            height: centerHeight
          }
        }
        a[b] = value
        return a
      }, {})
    }
    this.SectionItems = SectionItems
    this.setState({
      dataSource
    })
  }, 300)

  cellClick = currentValue => {
    this.historyItemClick(currentValue)
  }

  historyItemClick = currentValue => {
    this.setState({
      currentValue
    })
    const {
      navigation: {
        state: { params: { callback } = {} }
      },
      updateLandmark
    } = this.props
    callback && callback(currentValue)
    updateLandmark({
      cityName: currentValue
    })
    const query = {
      cityName: currentValue
    }
    this.props.userId && insertCityHistory({ query })
    this.props.navigation.goBack()
  }
}
export default CommonListCity
const styles = StyleSheet.create({
  naviTitle: {
    fontSize: ScaleT(17),
    fontWeight: '400',
    color: '#030303'
  },
  searchCont: {
    height: ScaleS(66),
    flexDirection: 'row',
    paddingHorizontal: ScaleS(20),
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  searchTitle: {
    fontSize: ScaleT(28),
    fontWeight: '500',
    color: '#232323'
  },
  textIputBg: {
    width: ScaleS(220),
    height: ScaleS(36),
    backgroundColor: '#F7F7F7',
    borderRadius: ScaleS(19),
    flexDirection: 'row'
  },
  textInput: {
    paddingHorizontal: ScaleS(20),
    flex: 1
  },
  searchBtn: {
    height: ScaleS(36),
    width: ScaleS(49),
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: ScaleS(20)
  },
  searchImg: {
    height: ScaleS(20),
    width: ScaleS(18)
  },
  listContainer: {
    flex: 1
  },
  sectionItem: {
    width: ScaleS(30),
    paddingRight: ScaleS(10),
    flexDirection: 'row',
    justifyContent: 'flex-end'
  },
  sectionText: {
    width: ScaleS(30),
    paddingRight: ScaleS(10),
    textAlign: 'right',
    fontSize: ScaleT(10),
    fontWeight: '400',
    color: '#FFC200'
  },
  sectionHeaderTit: {
    backgroundColor: '#FFFFFF',
    paddingTop: ScaleS(18),
    paddingLeft: ScaleS(20),
    height: ScaleS(46),
    lineHeight: ScaleS(28),
    fontSize: ScaleT(16),
    fontWeight: '400',
    color: '#000000'
  },
  cell: {
    marginHorizontal: ScaleS(20),
    height: ScaleS(50),
    justifyContent: 'center',
    borderColor: '#EFEFEF',
    borderStyle: 'solid',
    borderBottomWidth: ONE_PIXEL
  },
  cellTit: {
    fontSize: ScaleT(14),
    fontWeight: '400',
    color: '#444444'
  },
  headerContainer: {
    borderColor: '#EFEFEF',
    borderStyle: 'solid',
    borderTopWidth: ONE_PIXEL,
    borderBottomWidth: ONE_PIXEL,
    paddingHorizontal: ScaleS(20),
    paddingBottom: ScaleS(14)
  },
  historyTip: {
    lineHeight: ScaleS(66),
    fontSize: ScaleT(18),
    fontWeight: '400',
    color: '#999999'
  },
  historyCitys: {
    marginHorizontal: ScaleS(-4),
    flexDirection: 'row',
    flexWrap: 'wrap'
  },
  cityBtn: {
    marginHorizontal: ScaleS(3),
    backgroundColor: '#F7F7F7',
    width: ScaleS(108),
    height: ScaleS(43),
    marginBottom: ScaleS(10),
    justifyContent: 'center',
    alignItems: 'center'
  },
  cityText: {
    fontSize: ScaleT(14),
    fontWeight: '400',
    color: '#666666'
  }
})
